package com.jiangyao.common.utils;

import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.StringUtils;

import java.nio.charset.Charset;
import java.security.MessageDigest;

/**
 * MD5加密工具
 *
 * @author: yangyongchuan
 * @create: 2020年05月07日 17:47
 */
public final class MD5util {

	private MD5util() {
	}

	private static final String MD5 = "MD5";
	private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

	private static MessageDigest getMessageDigest() {
		try {
			return MessageDigest.getInstance(MD5);
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}


	public static String generateSymbol(String symbol) {
		if (StringUtils.isBlank(symbol)) {
			throw new NullPointerException("symbol must be not null or empty!");
		}
		byte[] bytes_utf8 = symbol.getBytes(Charset.forName(CharEncoding.UTF_8));
		return generateSymbol(bytes_utf8);
	}

	public static String generateSymbol(byte[] bytes_utf8) {
		byte[] bytes_md5 = getMessageDigest().digest(bytes_utf8);
		char str[] = new char[16 * 2];
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte byte0 = bytes_md5[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}
		return new String(str);
	}

	public static void main(String[] args) {
		System.out.println(generateSymbol("xx"));
	}
}
